package com.tanhua.dubbo.api;

import cn.hutool.core.collection.CollUtil;
import com.tanhua.model.mongo.UserLocation;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.geo.Circle;
import org.springframework.data.geo.Distance;
import org.springframework.data.geo.Metrics;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.geo.GeoJsonPoint;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;

import java.util.List;

@DubboService
public class UserLocationApiImpl implements UserLocationApi {

    @Autowired
    private MongoTemplate mongoTemplate;

    //保存或者更新
    public void save(Long userId, Double lat, Double lon, String address) {
        //1、查询当前用户的位置信息是否存在
        Query query = Query.query(Criteria.where("userId").is(userId));
        boolean exists = mongoTemplate.exists(query, UserLocation.class);
        if(!exists) {
            //2、如果信息不存在，保存
            UserLocation location = new UserLocation();
            location.setUserId(userId);
            location.setAddress(address);
            location.setCreated(System.currentTimeMillis());
            GeoJsonPoint point = new GeoJsonPoint(lon, lat);
            location.setLocation(point);
            mongoTemplate.save(location);
        }else {
            //3、如果信息存在，更新  update xxx set xxxxx  where userId=?
            Update update = new Update();
            update.set("location",new GeoJsonPoint(lon, lat));
            update.set("address",address);
            update.set("updated",System.currentTimeMillis());
            mongoTemplate.updateFirst(query,update,UserLocation.class); //条件，设置的字段，对象.class
        }
    }

    //搜索附近
    public List<Long> searchNear(Long userId, String miles) {
        //查询当前用户的地理位置数据
        Criteria criteria = Criteria.where("userId").is(userId);
        Query query = Query.query(criteria);
        UserLocation ul = mongoTemplate.findOne(query, UserLocation.class);
        //1、查找圆点（圆心）- 当前用户的位置
        GeoJsonPoint location = ul.getLocation();
        //2、绘制半径（搜索的距离）
        Distance distance = new Distance(Double.valueOf(miles) / 1000,Metrics.KILOMETERS);//距离，单位
        //3、绘制圆（圆点 + 半径）
        Circle circle = new Circle(location,distance);
        //4、在已有的位置数据中，查询圆所覆盖的所有点
        Criteria criteria1 = Criteria.where("location").withinSphere(circle);//坐标点，是否在圆内部
        Query query1 = Query.query(criteria1);
        List<UserLocation> list = mongoTemplate.find(query1, UserLocation.class);
        //5、返回附近人的id
        return CollUtil.getFieldValues(list,"userId",Long.class);
    }
}
